import os
import re
from PIL import Image, ImageDraw, ImageFont
from moviepy.editor import *
from datetime import datetime, timedelta

# 读取test.txt中的内容
with open('test.txt', 'r', encoding='utf-8') as f:
    contents = f.read()

# 获取所有图片名称及其对应的描述
img_dict = {}
for match in re.finditer(r'\[(.*?)\]\n(.*?)\n\n', contents, re.S):
    img_name = match.group(1)
    img_desc = match.group(2)
    img_dict[img_name] = img_desc.strip()

# 获取所有图片的时长
img_durations = []
for img_name in img_dict:
    img_path = os.path.join('images', img_name + '.jpg')
    with Image.open(img_path) as img:
        img_durations.append(img.info['duration'] / 1000)

# 读取subtitle.srt中的内容
subs = []
with open('subtitle.srt', 'r', encoding='utf-8') as f:
    for line in f:
        subs.append(line.strip())

# 提取所有字幕的时长
sub_durations = []
for i in range(0, len(subs), 4):
    start, end = subs[i+1].split(' --> ')
    start_sec = sum(float(x) * 60 ** i for i, x in enumerate(reversed(start.split(':'))))
    end_sec = sum(float(x) * 60 ** i for i, x in enumerate(reversed(end.split(':'))))
    sub_durations.append(end_sec - start_sec)

# 根据图片时长生成视频帧
frame_list = []
for img_name, duration in zip(img_dict.keys(), img_durations):
    img_path = os.path.join('images', img_name + '.jpg')
    img = Image.open(img_path)
    frames = int(duration * 25)  # 每秒25帧
    for i in range(frames):
        frame = img.copy()
        draw = ImageDraw.Draw(frame)
        font = ImageFont.truetype('arial.ttf', size=24)
        draw.text((10, 10), img_dict[img_name], font=font, fill=(255, 255, 255))
        frame_list.append(frame)

# 根据字幕时长生成视频
clips = []
start = 0
for sub_duration in sub_durations:
    end = start + sub_duration
    sub_frames = frame_list[int(start * 25):int(end * 25)]
    clip = ImageSequenceClip(sub_frames, fps=25)
    clips.append(clip)
    start = end

# 生成最终视频
final_clip = concatenate_videoclips(clips)
final_clip.write_videofile("output.mp4")
